package cn.lzx.org.service.impl;

import cn.lzx.basic.service.impl.BaseServiceImpl;
import cn.lzx.org.domain.Department;
import cn.lzx.org.mapper.DepartmentMapper;
import cn.lzx.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * DepartmentServiceImpl继承了BaseServiceImpl 实现了IDepartmentService
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 添加
     * @Transactional开启事务
     * @param department
     */
    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);
        if(department.getParent()==null || department.getParent().getId() == null){//你没有选择上级部门
            department.setDirPath("/" + department.getId());
        }else{
            Long id = department.getParent().getId(); //上级部门的id
            Department parentDept = departmentMapper.loadById(id);
            //上级部门的dirPath
            String dirPath = parentDept.getDirPath();
            //设置自己的dirPath
            department.setDirPath(dirPath + "/" + department.getId());
        }
        //修改dirPath
        departmentMapper.update(department);
    }
    /**
     * 修改
     * @Transactional开启事务
     * @param department
     */
    @Override
    @Transactional
    public void update(Department department) {
        if(department.getParent()==null || department.getParent().getId() == null){//你没有选择上级部门
            department.setDirPath("/" + department.getId());
        }else{
            Long id = department.getParent().getId(); //上级部门的id
            Department parentDept = departmentMapper.loadById(id);
            //上级部门的dirPath
            String dirPath = parentDept.getDirPath();
            //设置自己的dirPath
            department.setDirPath(dirPath + "/" + department.getId());
        }
        departmentMapper.update(department);
    }
    /**
     * 查询部门数
     * @return
     */
    @Override
    public List<Department> getDeptTree() {
        return departmentMapper.getDeptTree();
    }
}
